package com.hqyj.server.controller;

import com.hqyj.server.json.R;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.request.AuthQqRequest;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("/oauth")
public class RestAuthController {

    @Value("${justauth.appId}")
    private String appId;

    @Value("${justauth.appKey}")
    private String appKey;

    @Value("${justauth.backUrl}")
    private String callBackUrl;

    /*
    @RequestMapping("/render")
    public void renderAuth(HttpServletResponse response) throws IOException {

        AuthRequest authRequest = getAuthRequest();
        String url = authRequest.authorize(AuthStateUtils.createState());
        System.out.println("--------------justAuth生成的第三方登录的URL------------------");
        System.out.println(url);
        response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));

    }*/

    @RequestMapping("/render")
    public R renderAuth(HttpServletResponse response) throws IOException {

        AuthRequest authRequest = getAuthRequest();
        String url = authRequest.authorize(AuthStateUtils.createState());
        System.out.println("--------------justAuth生成的第三方登录的URL------------------");
        System.out.println(url);
        //必须把里面state值替换为thirdlogin,这个值是不能改的。
        String postFix = "&state=thirdlogin&scope=get_user_info";
        int pos = url.indexOf("&state=");

        url = url.substring(0,pos)+postFix;
        //response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));

        return R.success("生成第三方登录URL成功！",url);
    }

    @RequestMapping("/callback")
    public Object login(AuthCallback callback) {
        AuthRequest authRequest = getAuthRequest();
        return authRequest.login(callback);
    }

    private AuthRequest getAuthRequest() {
        return new AuthQqRequest(AuthConfig.builder()
                .clientId(appId)
                .clientSecret(appKey)
                .redirectUri(callBackUrl)
                .build());
    }
}